package input;

import force.Force;
import java.awt.Point;
import object.connector.Spring;
import object.mass.FixedMass;
import object.mass.Mass;
import sim.Assembly;
import sim.Simulation;

/**
 * A class that response to mouse dragging and clicking by creating
 * a Spring connecting the closest Mass to a Spring.
 * 
 * @author Niel Lebeck and Wynne Lok
 *
 */
public class MouseResponder {
    private static final double MOUSE_SPRING_K = 0.1;
    private Simulation mySim;
    private boolean myIsActive;
    private Mass myMouseMass;
    private Assembly myAssembly;

    /**
     * 
     * @param sim Simulation
     */
    public MouseResponder(Simulation sim) {
        mySim = sim;
        myIsActive = false;
    }

    /**
     * Delete the spring and mass associated with the mouse after
     * the mouse is released.
     */
    public void notifyReleased() {
        myIsActive = false;
        myMouseMass = null;
        mySim.removeAssembly(myAssembly);
        myAssembly = null;
    }

    /**
     * Prepare the MouseResponder to for a series of mouse dragging
     * events.
     */
    public void notifyPressed() {
        myIsActive = true;
        myAssembly = new Assembly(mySim);
        mySim.addAssembly(myAssembly);
    }

    /**
     * Move the Mass associated with the mouse in response to dragging.
     * @param p the Point at which the mouse drag event was registered
     */
    public void update(Point p) {
        if (myIsActive) {
            if (myMouseMass == null) {
                myMouseMass = new FixedMass(0, p.getX(), p.getY(), 0);
                //get closest mass and link with spring
                Mass closestMass = mySim.getClosestMass(myMouseMass);
                Spring linkSpring = new Spring(myMouseMass, closestMass,
                        Force.distanceBetween(myMouseMass.getCenter(),
                                closestMass.getCenter()), MOUSE_SPRING_K);
                myAssembly.add(myMouseMass);
                myAssembly.add(linkSpring);
            }
            myMouseMass.setCenter(p.getX(), p.getY());
        }
    }


}
